import os
import xml.etree.ElementTree as ET

def calculate_iou(box1, box2):
    # 计算两个框的交并比
    xmin1, ymin1, xmax1, ymax1 = box1
    xmin2, ymin2, xmax2, ymax2 = box2

    xi1 = max(xmin1, xmin2)
    yi1 = max(ymin1, ymin2)
    xi2 = min(xmax1, xmax2)
    yi2 = min(ymax1, ymax2)

    inter_area = max(xi2 - xi1, 0) * max(yi2 - yi1, 0)

    box1_area = (xmax1 - xmin1) * (ymax1 - ymin1)
    box2_area = (xmax2 - xmin2) * (ymax2 - ymin2)
    
    union_area = box1_area + box2_area - inter_area

    iou = inter_area / union_area if union_area != 0 else 0

    return iou

def process_xml(directory, target_box):
    for filename in os.listdir(directory):
        if not filename.endswith('.xml'):
            continue

        tree = ET.parse(os.path.join(directory, filename))
        root = tree.getroot()

        for obj in root.findall('object'):
            bbox = obj.find('bndbox')
            xmin = int(bbox.find('xmin').text)
            ymin = int(bbox.find('ymin').text)
            xmax = int(bbox.find('xmax').text)
            ymax = int(bbox.find('ymax').text)

            iou = calculate_iou(target_box, (xmin, ymin, xmax, ymax))

            if iou > 0.6:
                root.remove(obj)

        tree.write(os.path.join(directory, filename))

# 使用方法
process_xml('20230831_960_540_200_xml_one_class', (473, 249, 834, 416))
